import { useRef, useEffect } from "react";

export type Options = {
  target: any;
  capture?: any;
  once?: any;
  passive?: any;
};

const useEventListener = (
  eventName: string,
  handler: any,
  options: Options
) => {
  const handlerRef = useRef(handler);

  useEffect(() => {
    const targetElement = options.target || window;
    if (!targetElement?.addEventListener) {
      return;
    }

    const eventListener = (event) => {
      return handlerRef.current(event);
    };

    targetElement.addEventListener(eventName, eventListener, {
      capture: options.capture,
      once: options.once,
      passive: options.passive,
    });

    return () => {
      targetElement.removeEventListener(eventName, eventListener, {
        capture: options.capture,
      });
    };
  }, [eventName, options.capture, options.once, options.passive]);
};

export { useEventListener };
